package com.hjs.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *同步锁Lock
 * 1.显示锁，需要通过lock()上锁，unlock()解锁
 *
 *
 * @author hanjinsong
 * @date 2020-02-19 14:40
 */
public class TestLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket,"1111").start();
        new Thread(ticket,"222").start();
        new Thread(ticket,"333").start();
        new Thread(ticket,"444").start();
        new Thread(ticket,"555").start();
        new Thread(ticket,"666").start();
    }
}

class Ticket implements Runnable {

    private int tick = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {

        try {
            lock.lock();
            while (tick > 0) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() +":,剩余"+ --tick);
            }

        }finally {
            lock.unlock();
        }


    }
}